package top.dreamix.njitkit.ui.screen.yiban

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.google.accompanist.web.AccompanistWebViewClient
import com.google.accompanist.web.WebView
import com.google.accompanist.web.rememberWebViewState
import org.json.JSONObject

@Composable
fun ShuMeiCaptchaScreen(
    mode: String = "spatial_select",
    onReady: () -> Unit = {},
    onSuccess: (Map<String, Any?>) -> Unit = {},
    onError: (code: String?, message: String) -> Unit = { _, _ -> }
) {
    val context = LocalContext.current
    val state = rememberWebViewState("https://castatic.fengkongcloud.com/pr/v1.0.3/index.html")

    val webViewClient = remember(context) {
        object : AccompanistWebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, wrr: WebResourceRequest): Boolean {
                val uri = wrr.url
                return handleShuMeiScheme(uri, view, context, onReady, onSuccess, onError, mode)
            }
        }
    }

    WebView(
        state = state,
        client = webViewClient,
        modifier = Modifier.fillMaxSize(),
        onCreated = { webView ->
            webView.settings.javaScriptEnabled = true
            webView.settings.domStorageEnabled = true

            // 可选：注入 JS Bridge（备用）
            webView.addJavascriptInterface(ShuMeiBridge(), "ShuMeiNative")
        }
    )
}

@SuppressLint("JavascriptInterface")
private class ShuMeiBridge {
    @JavascriptInterface
    fun deliverNativeParams(jsonStr: String) {
        Log.d("ShuMeiBridge", "JS called deliverNativeParams: $jsonStr")
        // 实际参数注入由 shouldOverrideUrlLoading 触发，此接口为冗余保护
    }
}

private fun handleShuMeiScheme(
    uri: Uri,
    webView: WebView,
    context: Context,
    onReady: () -> Unit,
    onSuccess: (Map<String, Any?>) -> Unit,
    onError: (code: String?, message: String) -> Unit,
    mode: String
): Boolean {
    if (uri.scheme != "shumei") return false

    return when (uri.host) {
        "requestnativeparams" -> {
            val nativeParams = buildNativeParams(context, mode)
            val escapedJson = nativeParams.replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"")
            webView.evaluateJavascript("deliverNativeParams('$escapedJson')") {
                Log.d("ShuMei", "JS eval result: $it")
            }
            true
        }

        "onresult" -> {
            uri.getQueryParameter("data")?.let { encodedData ->
                try {
                    val decoded = Uri.decode(encodedData)
                    val json = JSONObject(decoded)
                    val method = json.getString("method")

                    when (method) {
                        "onReady" -> onReady()
                        // {rid=2025110802385273c4de4d2a6b4cda2a, pass=true, method=onSuccess}
                        "onSuccess" -> onSuccess(json.toMap())
                        "onError" -> {
                            val code = json.optString("code", null)
                            val msg = json.optString("message", json.optString("detail", "未知错误"))
                            onError(code, msg)
                        }
                    }
                } catch (e: Exception) {
                    Log.e("ShuMei", "解析 shumei://onresult 失败", e)
                    onError(null, "解析失败: ${e.message}")
                }
            }
            true
        }

        else -> false
    }
}

private fun buildNativeParams(context: Context, mode: String): String {
    val params = mapOf(
        "organization" to "IY3HadrRSlgwwKWo63gi",
        "appId" to "Yiban_Android",
        "https" to true,
        "mode" to mode,
        "data" to mapOf(
            "os" to "android",
            "sdkver" to "1.2.4",
        )
    )
    return JSONObject(params).toString()
}

private fun JSONObject.toMap(): Map<String, Any?> = keys().asSequence().associateWith {
    when (val value = get(it)) {
        is JSONObject -> value.toMap()
        is org.json.JSONArray -> {
            (0 until value.length()).map { i ->
                when (val item = value[i]) {
                    is JSONObject -> item.toMap()
                    else -> item
                }
            }
        }
        else -> value
    }
}